/**
 * 行政人员
 * */
import React, { useRef, useState, useEffect } from 'react';
import { Form, Button, Divider, message, Spin, Select } from 'antd';
import { withRouter } from 'umi';
import { PageContainer } from '@/molecules';
import { BottomAction } from '@/components';
import { useRequest, defaultFormatResult } from '@/hooks';
import EmployeeCard from '@/pages/EntryManage/components/EmployeeCard';
import { replaceToWaitEntry } from '@/pages/EntryManage/utils';
import useCandidateProcess from '@/pages/EntryManage/hooks/useCandidateProcess';
import { size } from 'lodash';
import LimitInput from '@/components/LimitInput';
import Card from '../../components/Card';

import DeviceConfigTable from './component/DeviceConfigTable';
import SendBackModal from '../component/SendBackModal';
import styles from './index.less';
import { postAdministrative, getAdministrativeList, getOfficeLocation, getOfficeStation } from '../services';

const { Option } = Select;
const formItemLayout = {
    labelCol: {
        span: 2
    },
    wrapperCol: {
        span: 6
    }
};
const formTableLayout = {
    labelCol: {
        span: 2
    },
    wrapperCol: {
        span: 22
    }
};
const formRemarkLayout = {
    labelCol: {
        span: 2
    },
    wrapperCol: {
        span: 10
    }
};
// IT 行政准备
const PROCESS_STATUS = 4;
const Administration = ({ form, location }) => {
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const { employeeCode } = user;
    const { getFieldDecorator, validateFieldsAndScroll, setFieldsValue } = form;

    const { entryPersonnelCode, contractOrganizationCode } = location.query;

    const [loadingType, setLoadingType] = useState(0);
    const [assetListData, setAssetListData] = useState([]);

    const [officeStationList, setOfficeStationList] = useState(undefined);

    const sendBackRef = useRef();

    // 获取办公地址
    const { data: locationList, run: fetchOfficeLocation, loading: officeLocationLoading } = useRequest(
        () => getOfficeLocation(contractOrganizationCode),
        {
            manual: true,
            ...defaultFormatResult
        }
    );
    // 获取工位
    const { run: fetchOfficeStation, loading: officeStationLoading } = useRequest(value => getOfficeStation(value), {
        manual: true,
        onSuccess: res => {
            const { code, msg, data } = res;
            if (code === 10000) {
                if (data.length < 1) {
                    message.error('当前办公地点下无空闲工位，请先到行政管理-工位管理功能新增工位');
                }
                setOfficeStationList(data);
            } else {
                message.error(msg);
                setOfficeStationList(undefined);
            }
        }
    });
    // 提交行政准备
    const { run: submitAdministrative, loading } = useRequest(value => postAdministrative(value), {
        manual: true,
        onSuccess: res => {
            if (res) {
                const { code, msg } = res;
                if (code === 10000) {
                    message.success(msg);
                    replaceToWaitEntry();
                } else {
                    message.error(msg);
                }
            }
        }
    });
    // 回退显示回填数据
    const { loading: dataLoading } = useRequest(() => getAdministrativeList(entryPersonnelCode), {
        refreshDeps: [entryPersonnelCode],
        onSuccess: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    if (size(data) > 0) {
                        const { remark, assetList = [], officeLocationCode, stationCode } = data;
                        if (officeLocationCode) {
                            fetchOfficeStation(officeLocationCode);
                        }
                        setAssetListData(assetList);

                        setFieldsValue({
                            remark,
                            officeLocationCode: officeLocationCode || undefined,
                            stationCode: stationCode || undefined
                        });
                    }
                } else {
                    message.error(msg);
                }
            }
        }
    });
    const handleSubmit = type => {
        setLoadingType(type);
        const param = {
            currentHandlerEmployeeCode: employeeCode,
            entryPersonnelCode,
            temporaryStorage: type
        };
        // type === 1 为暂存 不做校验
        if (type === 1) {
            const { assetList, officeLocationCode, remark, stationCode } = form.getFieldsValue();
            const assetListFilter = assetList.filter(Boolean).map(item => item);
            submitAdministrative({
                assetList: assetListFilter,
                officeLocationCode,
                remark,
                stationCode,
                ...param
            });
            return;
        }
        validateFieldsAndScroll({ scroll: { alignWithTop: true } }, (err, values) => {
            if (!err) {
                const { assetList, officeLocationCode, remark, stationCode } = values;
                const assetListFilter = assetList.filter(Boolean).map(item => item);
                submitAdministrative({
                    assetList: assetListFilter,
                    officeLocationCode,
                    remark,
                    stationCode,
                    ...param
                });
            }
        });
    };

    const handleChangeLocation = value => {
        fetchOfficeStation(value);
        setFieldsValue({ stationCode: undefined });
    };
    useEffect(() => {
        fetchOfficeLocation();
    }, []);
    // 校验是否当前是否可以提交
    const canAction = useCandidateProcess(entryPersonnelCode, PROCESS_STATUS, employeeCode);
    return (
        <PageContainer>
            <EmployeeCard employeeCode={entryPersonnelCode} isShowControls={false} style={{ marginBottom: '20px' }} />

            <Divider />
            <Spin spinning={dataLoading}>
                <Card
                    title="行政准备"
                    headBorder
                    bordered={false}
                    extra={
                        canAction ? (
                            <BottomAction>
                                <span className={styles.autoNotice}>自行通知人事负责人</span>
                                <Button
                                    onClick={() => {
                                        sendBackRef.current.show();
                                    }}
                                >
                                    退回
                                </Button>
                                <Button
                                    type="link"
                                    style={{ border: '1px solid #FF9E00' }}
                                    onClick={() => handleSubmit(1)}
                                    loading={loading && loadingType === 1}
                                >
                                    保存
                                </Button>
                                <Button
                                    type="primary"
                                    onClick={() => handleSubmit(0)}
                                    loading={loading && loadingType === 0}
                                >
                                    确定
                                </Button>
                            </BottomAction>
                        ) : null
                    }
                >
                    <Form {...formTableLayout} className={styles.tableCtr}>
                        <Form.Item>
                            <DeviceConfigTable
                                entryPersonnelCode={entryPersonnelCode}
                                canAction={canAction}
                                assetList={assetListData}
                                form={form}
                            />
                        </Form.Item>
                    </Form>
                    <Form {...formRemarkLayout}>
                        <Form.Item label="备注：">
                            {getFieldDecorator('remark')(
                                <LimitInput
                                    area
                                    maxLength={200}
                                    autoSize={{ minRows: 4, maxRows: 6 }}
                                    placeholder="请输入"
                                    disabled={!canAction}
                                />
                            )}
                        </Form.Item>
                    </Form>
                    <Divider />
                    <Card title="工位安排" headBorder bordered={false} className={styles.cardBox}>
                        <Form {...formItemLayout}>
                            <Form.Item label="办公地点">
                                {getFieldDecorator('officeLocationCode', {
                                    rules: [{ required: true, message: '请选择' }]
                                })(
                                    <Select
                                        onChange={handleChangeLocation}
                                        placeholder="请选择"
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                        disabled={!canAction}
                                        loading={officeLocationLoading}
                                    >
                                        {Array.isArray(locationList) &&
                                            locationList.map(item => (
                                                <Option value={item.officeLocationCode} key={item.officeLocationCode}>
                                                    {item.officeLocationName}
                                                </Option>
                                            ))}
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item label="工位">
                                {getFieldDecorator('stationCode', {
                                    rules: [{ required: true, message: '请选择' }]
                                })(
                                    <Select
                                        placeholder="请选择"
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                        disabled={!canAction || officeStationLoading || officeStationList?.length < 1}
                                        loading={officeStationLoading}
                                    >
                                        {officeStationList &&
                                            officeStationList?.map(item => (
                                                <Option value={item.stationCode} key={item.stationCode}>
                                                    {item.stationName}
                                                </Option>
                                            ))}
                                    </Select>
                                )}
                            </Form.Item>
                        </Form>
                    </Card>
                </Card>
            </Spin>
            <SendBackModal
                entryPersonnelCode={entryPersonnelCode}
                wrappedComponentRef={sendBackRef}
                waringMessage="退回至IT部门，重新提交准备内容"
            />
        </PageContainer>
    );
};
export default withRouter(Form.create()(Administration));
